<?php

namespace App\Http\Controllers;

use App\Models\BillExport;
use App\Models\MoneyTransaction;
use App\Jobs\ProcessBillExportJob;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;

class BillExportController extends Controller
{
    /**
     * 显示账单导出页面
     */
    public function index()
    {
        if (!\Auth::user()->isMember()) return redirect()->route('membership.benefits');
        return view('user.bill-export');
    }

    /**
     * 获取导出历史记录
     */
    public function history(Request $request)
    {
        $user = Auth::user();

        $exports = BillExport::where('user_id', $user->id)
            ->with('book:id,name')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        $data = $exports->map(function ($export) {
            return [
                'id' => $export->id,
                'title' => $export->title,
                'book_name' => $export->book->name ?? '未知账本',
                'format' => $export->getFormatText(),
                'status' => $export->status,
                'status_text' => $export->getStatusText(),
                'created_at' => $export->created_at->format('Y-m-d H:i'),
                'expires_at' => $export->expires_at ? $export->expires_at->format('Y-m-d H:i') : null,
                'remaining_time' => $export->getRemainingTimeText(),
                'download_url' => $export->getDownloadUrl(),
                'is_expired' => $export->isExpired(),
                'error_message' => $export->error_message,
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $data,
            'pagination' => [
                'current_page' => $exports->currentPage(),
                'last_page' => $exports->lastPage(),
                'per_page' => $exports->perPage(),
                'total' => $exports->total(),
            ]
        ]);
    }

    /**
     * 提交导出申请
     */
    public function store(Request $request)
    {
        $user = Auth::user();

        // 检查是否为会员
        if (!$user->isMember()) {
            return response()->json([
                'success' => false,
                'message' => '账单导出功能仅限会员使用，请先升级会员'
            ], 403);
        }

        // 检查今日导出次数限制
        $todayExports = BillExport::where('user_id', $user->id)
            ->whereDate('created_at', today())
            ->count();

        if ($todayExports >= 2) {
            return response()->json([
                'success' => false,
                'message' => '每日最多可导出2次，您今日的导出次数已用完'
            ], 429);
        }

        // 验证请求数据
        $validator = Validator::make($request->all(), [
            'export_range' => 'required|in:all,month,custom',
            'start_date' => 'required_if:export_range,custom|date',
            'end_date' => 'required_if:export_range,custom|date|after_or_equal:start_date',
            'format' => 'required|in:excel,csv,pdf',
        ], [
            'export_range.required' => '请选择导出范围',
            'export_range.in' => '导出范围选择无效',
            'start_date.required_if' => '请选择开始日期',
            'start_date.date' => '开始日期格式无效',
            'end_date.required_if' => '请选择结束日期',
            'end_date.date' => '结束日期格式无效',
            'end_date.after_or_equal' => '结束日期不能早于开始日期',
            'format.required' => '请选择导出格式',
            'format.in' => '导出格式选择无效',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        // 获取用户默认账本
        $book = $user->getCurrentDefaultBook();
        if (!$book) {
            return response()->json([
                'success' => false,
                'message' => '您还没有账本，无法导出数据'
            ], 400);
        }

        // 确定导出范围和标题
        $exportRange = $request->export_range;
        $startDate = null;
        $endDate = null;
        $title = '';

        switch ($exportRange) {
            case 'all':
                $title = '全部记录导出';
                break;
            case 'month':
                $startDate = now()->startOfMonth()->toDateString();
                $endDate = now()->endOfMonth()->toDateString();
                $title = now()->format('Y年m月') . '记录导出';
                break;
            case 'custom':
                $startDate = $request->start_date;
                $endDate = $request->end_date;
                $start = Carbon::parse($startDate);
                $end = Carbon::parse($endDate);
                $title = $start->format('Y年m月d日') . '至' . $end->format('Y年m月d日') . '记录导出';
                break;
        }

        // 创建导出记录
        $export = BillExport::create([
            'user_id' => $user->id,
            'book_id' => $book->id,
            'title' => $title,
            'export_range' => $exportRange,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'format' => $request->input('format'),
            'status' => 'pending',
            'expires_at' => now()->addDays(3), // 3天后过期
        ]);

        // 分发异步任务
        ProcessBillExportJob::dispatch($export);

        return response()->json([
            'success' => true,
            'message' => '导出申请已提交，系统正在处理中，完成后将通过微信通知您',
            'export_id' => $export->id
        ]);
    }

    /**
     * 下载导出文件
     */
    public function download($id)
    {
        $user = Auth::user();

        $export = BillExport::where('id', $id)
            ->where('user_id', $user->id)
            ->first();

        if (!$export) {
            abort(404, '导出记录不存在');
        }

        if ($export->status !== 'completed') {
            abort(400, '文件尚未生成完成');
        }

        if ($export->isExpired()) {
            abort(410, '文件已过期');
        }

        if (!$export->file_path || !Storage::disk('exports')->exists($export->file_path)) {
            abort(404, '文件不存在');
        }

        $filename = $export->title . '.' . $export->format;
        
        // 检测是否为微信环境
        $userAgent = request()->header('User-Agent', '');
        $isWeChat = strpos($userAgent, 'MicroMessenger') !== false;
        
        // 如果是AJAX请求或微信环境，返回下载链接
        if (request()->ajax() || $isWeChat) {
            $downloadUrl = Storage::disk('exports')->url($export->file_path);
            
            return response()->json([
                'success' => true,
                'download_url' => $downloadUrl,
                'filename' => $filename,
                'is_wechat' => $isWeChat,
                'message' => $isWeChat ? '请在浏览器中打开链接下载文件' : '获取下载链接成功'
            ]);
        }

        // 普通浏览器直接下载
        return Storage::disk('exports')->download($export->file_path, $filename);
    }

    /**
     * 公开下载文件（免登录）
     */
    public function publicDownload($token)
    {
        $export = BillExport::where('download_token', $token)->first();

        if (!$export) {
            abort(404, '下载链接不存在或已失效');
        }

        if ($export->status !== 'completed') {
            abort(400, '文件尚未生成完成');
        }

        if ($export->isExpired()) {
            abort(410, '文件已过期');
        }

        if (!$export->file_path || !Storage::disk('exports')->exists($export->file_path)) {
            abort(404, '文件不存在');
        }

        $filename = $export->title . '.' . $export->format;

        return Storage::disk('exports')->download($export->file_path, $filename);
    }

    /**
     * 获取公开下载URL
     */
    public function getPublicUrl($id)
    {
        $export = BillExport::where('id', $id)
            ->where('user_id', auth()->id())
            ->first();

        if (!$export) {
            return response()->json([
                'success' => false,
                'message' => '导出记录不存在'
            ], 404);
        }

        if ($export->status !== 'completed') {
            return response()->json([
                'success' => false,
                'message' => '文件尚未生成完成'
            ], 400);
        }

        if ($export->isExpired()) {
            return response()->json([
                'success' => false,
                'message' => '文件已过期'
            ], 410);
        }

        $publicUrl = $export->getPublicDownloadUrl();
        if (!$publicUrl) {
            return response()->json([
                'success' => false,
                'message' => '无法生成下载链接'
            ], 500);
        }

        return response()->json([
            'success' => true,
            'download_url' => $publicUrl,
            'filename' => $export->title . '.' . $export->format
        ]);
    }

    /**
     * 检查导出状态
     */
    public function checkStatus($id)
    {
        $user = Auth::user();

        $export = BillExport::where('id', $id)
            ->where('user_id', $user->id)
            ->first();

        if (!$export) {
            return response()->json([
                'success' => false,
                'message' => '导出记录不存在'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => [
                'id' => $export->id,
                'status' => $export->status,
                'status_text' => $export->getStatusText(),
                'download_url' => $export->getDownloadUrl(),
                'remaining_time' => $export->getRemainingTimeText(),
                'error_message' => $export->error_message,
            ]
        ]);
    }
}
